using System;
using System.Data;
using MyClever.Lib;

namespace MyClever.DefaultPlugins
{
    public class ReplaceText : MissionPlugin
    {
        [Package(Direction.Input, "Defines the origin package in which we like mapping the data.")]
        enum OriginPackage { }

        [Package(Direction.Input, "A ruleset which defines the rename-process.")]
        enum ReplaceNorm 
        {
            [Column(typeof(string), "The column in which we like to start the text replace process.")]
            ColumnName,
            [Column(typeof(string), "The string which should be replace with the SubstitutionString.")]
            OldValue,
            [Column(typeof(string), "The string which substitute the old ExchangeableString.")]
            NewValue
        }

        [Package(Direction.Output, "The new package with all mapped data.")]
        enum Output
        { }

        [Plugin(PluginDevStatus.Production, "Replace a string with another in the expected column.")]
        public ReplaceText()
        {
        }

        public override void Initialize()
        {
            //This is the first Function called by the host...
            //Put anything needed to start with here first
        }

        public override void Dispose()
        {
            //Put any cleanup code in here for when the program is stopped
        }

        protected override void Work()
        {
            MissionPluginPackage outputPackage = this.GetPackageByName(typeof(Output));
            outputPackage.CopyDataFromPackage(this.GetPackageByName(typeof(OriginPackage)));

            DataTableReader mappingNormPackage = this.GetDataReader(typeof(ReplaceNorm));
            while (mappingNormPackage.Read())
            {
                string oldValue = mappingNormPackage[ReplaceNorm.OldValue.ToString()].ToString();
                string newValue = mappingNormPackage[ReplaceNorm.NewValue.ToString()].ToString();
                string columnName = mappingNormPackage[ReplaceNorm.ColumnName.ToString()].ToString();

                this.AddNewLoggingMessage(typeof(ReplaceNorm), String.Format("replace {0} with {1} in column {2}", oldValue, newValue, columnName));
               
                foreach (DataRow rowOn in outputPackage.Rows)
	            {
                    rowOn[columnName] = rowOn[columnName].ToString().Replace(oldValue, newValue);
	            }
            }
        }  
    }
}
